package com.twu.biblioteca;

public class MenuController extends AbstractController {

    private final BibliotecaApp app;

    private ReserveController reserveController;

    private LoginController loginController;

    private SecurityContext securityContext;

    public MenuController(BibliotecaApp app) {
        this.app = app;
        setUserInterface(app.getUserInterface());
    }

    public void setReserveController(ReserveController reserveController) {
        this.reserveController = reserveController;
    }

    public void setLoginController(LoginController loginController) {
        this.loginController = loginController;
    }

    public void setSecurityContext(SecurityContext securityContext) {
        this.securityContext = securityContext;
    }

    public void enter() {
        getUserInterface().showMenu();
    }

    public Controller handle(String input) {
        return select(input);
    }

    /* default */ Controller select(String menuOption) {
        final Controller result;
        if ("list".equals(menuOption)) {
            result = doList();
        } else if ("membership".equals(menuOption)) {
            result = doMembership();
        } else if ("reserve".equals(menuOption)) {
            result = doReserve();
        } else if ("movies".equals(menuOption)) {
            result = doMovies();
        } else if ("login".equals(menuOption)) {
            result = loginController;
        } else if ("quit".equals(menuOption)) {
            result = doQuit();
        } else {
            getUserInterface().showInvalidCommandMessage(menuOption);
            result = this;
        }
        return result;
    }

    private Controller doList() {
        getUserInterface().showBookList(app.getBookShelf().findAll());
        return this;
    }

    private Controller doMembership() {
        if (securityContext.isUserLoggedIn() == true) {
            getUserInterface().showMembershipInfo(securityContext.getUser());
        } else {
            getUserInterface().showLoginRequiredMessage();
        }
        return this;
    }

    private Controller doMovies() {
        getUserInterface().showMovieList(app.getMovieRepository().findAll());
        return this;
    }

    private Controller doReserve() {
        final Controller result;
        if (SecurityContext.get().isUserLoggedIn() == true) {
            result = reserveController;
        } else {
            getUserInterface().showLoginRequiredMessage();
            result = this;
        }
        return result;
    }

    private Controller doQuit() {
        app.quit();
        return null;
    }

}
